#!/bin/sh -e
### BEGIN INIT INFO
# Provides:          pulseaudio esound
# Required-Start:    $remote_fs $syslog dbus
# Required-Stop:     $remote_fs $syslog dbus
# Should-Start:      dbus
# Should-Stop:       dbus
# Default-Start:     2 3 4 5
# Default-Stop:      1
# Short-Description: Start the PulseAudio sound server
# Description:       System mode startup script for
#                    the PulseAudio sound server.
### END INIT INFO

DAEMON=/usr/bin/pulseaudio
PIDFILE=/var/run/pulse/pid 
PATH=/sbin:/bin:/usr/sbin:/usr/bin

test -x $DAEMON || exit 0

. /lib/lsb/init-functions

PULSEAUDIO_SYSTEM_START=0
DISALLOW_MODULE_LOADING=1
test -f /etc/default/pulseaudio && . /etc/default/pulseaudio

pulseaudio_start () {
	test "$PULSEAUDIO_SYSTEM_START" != "1" && exit 0
	log_begin_msg "Starting PulseAudio Daemon"
	start-stop-daemon -x $DAEMON -p $PIDFILE --start -- --system --daemonize --high-priority --log-target=syslog --disallow-module-loading=$DISALLOW_MODULE_LOADING
	status=$?
	if [ -e /var/run/pulse/.esd_auth ]; then
		chown pulse:pulse-access /var/run/pulse/.esd_auth
		chmod 640 /var/run/pulse/.esd_auth
	fi
	if [ -e /var/run/pulse/.pulse-cookie ]; then
		chown pulse:pulse-access /var/run/pulse/.pulse-cookie
		chmod 640 /var/run/pulse/.pulse-cookie
	fi
	log_end_msg ${status}
}

pulseaudio_stop () {
	log_begin_msg "Stopping PulseAudio Daemon"
	start-stop-daemon -p $PIDFILE --stop --retry 5 || echo -n "... pulseaudio is not running"
	log_end_msg $?
}

case "$1" in
	start|stop)
		pulseaudio_${1}
		;;
	restart|reload|force-reload)
		pulseaudio_stop
		pulseaudio_start
		;;
	force-stop)
		pulseaudio_stop
		killall pulseaudio || true
		sleep 2
		killall -9 pulseaudio || true
		;;
	status)
		status_of_proc $DAEMON pulseaudio -p $PIDFILE
		exit $?
		;;
	*)
		echo "Usage: /etc/init.d/pulseaudio {start|stop|force-stop|restart|reload|force-reload|status}"
		exit 1
		;;
esac

exit 0
